import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'

// Routes that do not require authentication
const WHITE_LIST: string[] = ['/login','/deng']

export function withAuthGuard<P extends object>(Component: React.ComponentType<P>) {
	const Guard: React.FC<P> = (props) => {
		const { pathname } = useLocation()
		const token = localStorage.getItem('token')

		if (!token && !WHITE_LIST.includes(pathname)) {
			return <Navigate to="/login" replace state={{ from: pathname }} />
		}

		if (token && pathname === '/login') {
			return <Navigate to="/index" replace />
		}

		return <Component {...props} />
	}

	Guard.displayName = `WithAuthGuard(${Component.displayName || Component.name || 'Component'})`
	return Guard
}

export default withAuthGuard


